package de.gwtprime.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import de.gwtprime.server.model.User;
import de.gwtprime.server.sql.HibernateEntityMangerSingelton;
import de.gwtprime.util.Helper;

/**
 * If a user subscribes, he gets an email with an activation email.
 * The link directs to this servlet. Email and hash are validated and the user
 * is activated.
 */
public class ActivationServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * Logger
	 */
	private static Logger logger = Logger.getLogger(ActivationServlet.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		
		PrintWriter writer = resp.getWriter();
		writer.println("<html>");
		writer.println("<head>");
		writer.println("<link type=\"text/css\" rel=\"stylesheet\" href=\"servletCSS.css\"");
		writer.println("</head>");
		writer.println("<body>");
		writer.println("<div class=\"servletMessage\">");
		
		String email = req.getParameter("email");
		String hash = req.getParameter("hash");
		
		if(Helper.isNullOrEmpty(email) || Helper.isNullOrEmpty(hash)){
			logger.error("Activation failed. 'email' or 'hash'-parameter are empty");
			
			writer.println("Activation failed! Url is not correct.");
			return;
		}
		EntityManager entityManager =null;
		try{
		EntityManagerFactory entityManagerFactory = HibernateEntityMangerSingelton.getEntityManagerFactory();
		entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
		
		Query query = entityManager.createQuery(String.format("from User where email = '%s' AND activationHash = '%s'", email, hash));
		query.setMaxResults(1); 
		
		if(query.getResultList().size()>0){
			
			User u = (User)query.getResultList().get(0);
			
			if(u.isActive()){
				logger.info("User "+email+" is already activated.");
				writer.println("User <b>"+email+"</b> is already activated.");
				return;
			}
			
			
			u.setActive(true);
			
			//entityManager.getTransaction().begin();
			entityManager.persist(u);
			entityManager.getTransaction().commit();
			
			logger.info("User "+email+" was successfully activated.");
			writer.println("User "+email+" was successfully activated.");
			
		}else{
			logger.warn("There is no user with email: "+email+" and hash: "+hash);
			writer.println("There is no user with email: "+email+" and hash: "+hash);
			return;
		}
		}catch(Exception e){
			logger.error(e);
			writer.println(e);
		}finally{
			entityManager.close();
			writer.println("</div>");
			writer.println("</body>");
			writer.println("</html>");
		}
		
		EntityManagerFactory entityManagerFactory = HibernateEntityMangerSingelton.getEntityManagerFactory();
		entityManager = entityManagerFactory.createEntityManager();
		entityManager.getTransaction().begin();
	
	}

}
